define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'csmitsm_xcore', 'csmitsm_xcflow'],
    function ($, undefined, Backend, Table, Form, xcore, xcflow) {
        var const_string_types = ["xcform_control_input_string", "xcform_control_input_number", "xcform_control_input_date", "xcform_control_objselect", "xcform_control_select"];
        var const_all_types = ["xcform_control_input_string", "xcform_control_input_number", "xcform_control_input_date", "xcform_control_objselect", "xcform_control_select"];
        
        var debounce_saveSubmit = xcore.debounce(function (that) {
            Fast.api.ajax({
                url: Fast.api.fixurl("csmitsm/xcflowviewpageview/saveSubmit"),
                type: "post",
                data: that.settingcontrol.form,
            }, function (res) {
                that._renderViewTable(that.settingcontrol.form.showfields);
                return false;
            });
        }, 1000);
        
        var Controller = {

            configview: function () {
                var that = this;
                new Vue({
                    el: '#app',
                    data: function () {
                        return {
                            sp: {
                                view_id: Config.view_id,
                                page_id: Config.page_id,
                                views: Config.views,
                                view: Config.view,
                                tables: Config.tables,
                            },
                            dict: {
                                slabel: [{
                                        code: 'base',
                                        label: '基本设置'
                                    },
                                    {
                                        code: 'show',
                                        label: '查询结果'
                                    },
                                    // {
                                    //     code: 'query',
                                    //     label: '查询条件'
                                    // },
                                    {
                                        code: 'order',
                                        label: '数据排序'
                                    },
                                    {
                                        code: 'filter',
                                        label: '数据筛选'
                                    },
                                    {
                                        code: 'delete',
                                        label: '删除视图'
                                    },
                                ],
                                orderby: [{
                                        code: 'asc',
                                        name: '升序'
                                    },
                                    {
                                        code: 'desc',
                                        name: '降序'
                                    }
                                ],
                                el: [{
                                        code: 'EQ',
                                        name: '等于',
                                        types: const_string_types
                                    },
                                    {
                                        code: 'NEQ',
                                        name: '不等于',
                                        types: const_string_types
                                    },
                                    {
                                        code: 'LIKE',
                                        name: '包含(Like %%)',
                                        types: ["xcform_control_input_string", "xcform_control_input_text"]
                                    },
                                    {
                                        code: 'NOT LIKE',
                                        name: '包含(NOT Like %%)',
                                        types: ["xcform_control_input_string", "xcform_control_input_text"]
                                    },
                                    {
                                        code: "GT",
                                        name: '>',
                                        types: ["xcform_control_input_number", "xcform_control_input_date", "xcform_control_input_datetime"]
                                    },
                                    {
                                        code: 'EGT',
                                        name: '>=',
                                        types: ["xcform_control_input_number", "xcform_control_input_date", "xcform_control_input_datetime"]
                                    },
                                    {
                                        code: 'LT',
                                        name: '<',
                                        types: ["xcform_control_input_number", "xcform_control_input_date", "xcform_control_input_datetime"]
                                    },
                                    {
                                        code: 'ELT',
                                        name: '<=',
                                        types: ["xcform_control_input_number", "xcform_control_input_date", "xcform_control_input_datetime"]
                                    },
                                    {
                                        code: 'BETWEEN',
                                        name: '范围',
                                        types: ["xcform_control_input_number", "xcform_control_input_date", "xcform_control_input_datetime"]
                                    },
                                    {
                                        code: 'in',
                                        name: '包含(in)',
                                        types: const_string_types
                                    },
                                    {
                                        code: 'notin',
                                        name: '不包含(not in)',
                                        types: const_string_types
                                    },
                                    {
                                        code: 'NULL',
                                        name: '为空',
                                        types: const_all_types
                                    },
                                    {
                                        code: 'NOT NULL',
                                        name: '不为空',
                                        types: const_all_types
                                    },
                                    {
                                        code: 'in_sql',
                                        name: 'IN SQL',
                                        types: const_all_types
                                    },
                                ]
                            },
                            sr: {
                                xcfieldjsonObj: [], // [{fieldcode:"xxx"}]
                                xcfieldjsonKeyObj: [], // ["xxx"=>{fieldcode:"xxx"}]
                                showfields: Config.view.configjsonObj ? Config.view.configjsonObj.showfields : null,
                                filterfields: Config.view.configjsonObj ? Config.view.configjsonObj.filterfields : null,
                                orderbyfields: Config.view.configjsonObj ? Config.view.configjsonObj.orderbyfields : null,
                                remoteObjselectOptions: [], //{"fa_test"=>[]}
                            },
                            settingcontrol: {
                                visible: false,
                                slabel: 'base',
                                form: {
                                    view_id: Config.view_id,
                                    page_id: Config.page_id,
                                    name: Config.view.name,
                                    tablename: Config.view.tablename,
                                    showfields: [],
                                    filterfields: [],
                                    filtersql: Config.view.configjsonObj ? Config.view.configjsonObj.filtersql : null,
                                    orderbyfields: [],
                                },
                                rules: {
                                    name: [{
                                        required: true,
                                        message: '请输入',
                                        trigger: 'blur'
                                    }]
                                }
                            }
                        };
                    },
                    watch: {
                        'settingcontrol.form': {
                            handler(newVal, oldVal) {
                                let that = this;
                                if (that.$refs["settingform"]) {
                                    that.$refs["settingform"].validate(function (valid) {
                                        if (valid) {
                                            debounce_saveSubmit(that);
                                        }
                                    });
                                }
                            },
                            deep: true
                        },
                        'settingcontrol.form.tablename': {
                            handler(newVal, oldVal) {
                                let that = this;
                                that._loadXcfieldjsonObj();
                            },
                        },
                        // sync view_tab_name
                        'settingcontrol.form.name': {
                            handler(newVal, oldVal) {
                                let that = this;
                                console.log('===',that.sp.views,that.sp.view_id);
                                for(var index in that.sp.views){
                                    if(that.sp.views[index]['id']==that.sp.view_id){
                                        that.sp.views[index]['name'] = newVal;
                                    }
                                }
                            },
                        }
                    },
                    mounted() {
                        var that = this;
                        that._loadXcfieldjsonObj();
                    },
                    methods: {
                        click_setting: function () {
                            var that = this;
                            that.settingcontrol.visible = true;
                        },
                        click_tabView(view_id) {
                            var that = this;
                            window.location.href = Fast.api.fixurl("csmitsm/xcflowviewpageview/configview?view_id=" + view_id + "&page_id=" + Config.page_id);
                        },
                        click_tabAdd() {
                            var that = this;
                            window.location.href = Fast.api.fixurl("csmitsm/xcflowviewpageview/addConfigview?page_id=" + Config.page_id);
                        },
                        control_clickDbviewMng() {
                            var that = this;
                            xcore.openWindow(Fast.api.fixurl("csmitsm/xcflowdbview/index"));
                        },
                        control_refreshDbview() {
                            var that = this;
                            //xoto
                        },
                        control_dragView(t) {
                            var that = this;
                            var ids = [];
                            for (var index in that.sp.views) {
                                ids.push(that.sp.views[index]['id']);
                            }
                            Fast.api.ajax({
                                url: Fast.api.fixurl("ajax/weigh"),
                                type: "post",
                                data: {
                                    ids: ids.join(','),
                                    changeid: that.sp.views[t['newIndex']]['id'],
                                    field: "weigh",
                                    orderway: "asc",
                                    table: "csmitsm_xcflowviewpageview",
                                    pk: "id"
                                },
                            }, function (res) {
                                return false;
                            });

                        },
                        click_deleteView() {
                            var that = this;
                            this.$confirm('确认是否删除?', '确认信息').then(function () {
                                window.location.href = Fast.api.fixurl("csmitsm/xcflowviewpageview/deleteConfigview?view_id=" + Config.view_id + "&page_id=" + Config.page_id);
                            });
                        },
                        _loadXcfieldjsonObj() {
                            var that = this;
                            if (that.settingcontrol.form.tablename != null) {
                                Fast.api.ajax({
                                    url: Fast.api.fixurl("csmitsm/xcflowviewpageview/getXcformjsonByTablename"),
                                    type: "get",
                                    data: {
                                        "tablename": that.settingcontrol.form.tablename
                                    },
                                }, function (res) {
                                    that.sr.xcfieldjsonObj = res.xcfieldjsonObj;
                                    that.sr.xcfieldjsonKeyObj = xcflow.tool_getXcfieldjsonKeyObj(that.sr.xcfieldjsonObj);

                                    var showfields = that._loadXcfieldjsonObj_getFormfields(res.xcfieldjsonObj, 'showfields');
                                    that._setIdfieldSelected(showfields); 
                                    that.settingcontrol.form["showfields"] = showfields;
                                    
                                    that.settingcontrol.form["orderbyfields"] = that._loadXcfieldjsonObj_getFormfields(res.xcfieldjsonObj, 'orderbyfields');
                                    that.settingcontrol.form["filterfields"] = that._loadXcfieldjsonObj_getFormfields(res.xcfieldjsonObj, 'filterfields');
                                    that._renderViewTable(that.settingcontrol.form.showfields);
                                    return false;
                                });
                            }
                        },
                        _setIdfieldSelected(fields){
                            var that = this;
                            for(var index in fields){
                                if(fields[index]['fieldcode']=='id'){
                                    fields[index]['selected'] = "Y";
                                }
                            }
                        },
                        _loadXcfieldjsonObj_getFormfields(xcfieldjsonObj, label) {
                            var that = this;
                            // full fieldcode set , and use label_json while exists
                            var results = [];
                            for (var index in xcfieldjsonObj) {
                                var isFoundItem = null;
                                for (var index2 in that.sr[label]) {
                                    var item2 = that.sr[label][index2];
                                    if (that.sr[label][index2]['fieldcode'] == xcfieldjsonObj[index]["fieldcode"]) {
                                        isFoundItem = item2;
                                    }
                                }
                                if (isFoundItem) {
                                    // title change by xcform's field_title change
                                    isFoundItem['title'] = xcfieldjsonObj[index]['title'];
                                    results.push(isFoundItem);
                                } else {
                                    results.push({
                                        title: xcfieldjsonObj[index]['title'],
                                        fieldcode: xcfieldjsonObj[index]['fieldcode'],
                                        selected: "N"
                                    });
                                }
                            }
                            return results;
                        },
                        _renderViewTable(showfields) {
                            var that = this;
                            xcflow.listpage_renderViewTable(Config.view.xcflowviewpage_id, Config.view.id, that.sr.xcfieldjsonObj, showfields);

                            // xcflow.listpage_renderViewTable(Config.view.xcflowviewpage_id, Config.view.id, showfields);
                        },
                        change_changeDatetime(item, key) {
                            var that = this;
                            item[key] = parseInt(item[key + "_ts"]) / 1000;
                        },
                        control_remoteSelectObj(query, tablename) {
                            var that = this;
                            Fast.api.ajax({
                                url: Fast.api.fixurl("csmitsm/xcflowviewpageview/getTableDatasByTablename"),
                                type: "get",
                                data: {
                                    tablename: tablename
                                },
                            }, function (res) {
                                var tt = {};
                                tt[tablename] = res.list;
                                that.sr.remoteObjselectOptions = tt;
                                return false;
                            });
                        },
                        handleVisibleChange(visible, tablename) {
                            var that = this;
                            if (visible) {
                                that.control_remoteSelectObj('', tablename);
                            }
                        }
                    }
                });
            },

        };
        return Controller;
    });